#!/usr/bin/python3

'''
Created on 2013-1-19

@author: PC
'''

# Account configuration
# Mobile phone
USERNAME = ''
# password
PASSWORD = ''

from urllib.parse import urlencode
from urllib.request import urlopen
import hashlib
import time

def main():
    while True:
        time.sleep(1)
        try:
            if not isnetworkavailable():
                sendLoginRequest()
            else:
                print('network is available')
        except Exception as ex:
            print(ex)

def isnetworkavailable():
    try:
        url = 'http://www.baidu.com/'
        response = urlopen(url, timeout=1)
        html = str(response.read())
        if 'Web Authentication Redirect' in html:
            return False
        return True
    except Exception as ex:
        print(ex)
        return False

def sendLoginRequest():
    spaceCount = 0
    userName = USERNAME
    password = PASSWORD
    form = {'buttonClicked':'4',
            'redirect_url':'',
            'err_flag':'0',
            'username':userName,
            'password':password}
    formText = bytes(urlencode(form), 'utf8')
    url = 'https://wifi.zjgsu.edu.cn/login.html'
    response = urlopen(url, timeout=1, data=formText)
    print(md5(response.read()))

def md5(data):
    return hashlib.md5(data).hexdigest()

if __name__=='__main__':
    main()
